package com.dwyinyuan.producer;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.concurrent.BlockingQueue;

public class YalayiProducer implements Runnable {

    private String name;
    private BlockingQueue<String> blockingQueue;

    public YalayiProducer(String name, BlockingQueue<String> blockingQueue) {
        this.name = name;
        this.blockingQueue = blockingQueue;
    }

    private static final String[] YALAYI_PREFIXS = {
            //最新
            "https://www.yalayi.com/gallery",
//            "https://www.yalayi.com/gallery/index_2.html",
//            "https://www.yalayi.com/gallery/index_3.html",
//            "https://www.yalayi.com/gallery/index_4.html",
//            "https://www.yalayi.com/gallery/index_5.html",
//            "https://www.yalayi.com/gallery/index_6.html",
//            "https://www.yalayi.com/gallery/index_7.html",
//            "https://www.yalayi.com/gallery/index_8.html",
//            "https://www.yalayi.com/gallery/index_9.html",
//            //精品
//            "https://www.yalayi.com/selected",
    };

    @Override
    public void run() {

        Document document = null;
        try {
            for (String url : YALAYI_PREFIXS) {
                document = Jsoup.connect(url).get();

                Elements elements = document.getElementsByClass("img-box");
                for (Element imgBoxElement : elements) {

                    String detail_url = imgBoxElement.getElementsByTag("a").first().attr("href");
                    document = Jsoup.connect(detail_url).get();
                    Elements bigimg = document.getElementsByClass("lazy");
                    for (Element img : bigimg) {
                        String attr = img.attr("data-original");
                        String replace = attr.replace("!pcimg", "");
                        blockingQueue.put(replace);
                        System.out.println(name + " put： " + replace);
                    }
                }
            }
            //消费者根据""退出while循环
            blockingQueue.put("");
            System.out.println("-----------------------------------");
            System.out.println(name + " is over");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
